//
//  LEAlertView.m
//  CreditAddressBook
//
//  Created by LE on 15/12/14.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "LEAlertView.h"
#import <QuartzCore/QuartzCore.h>
#import "UIImage+ImageEffects.h"
#import "UIWindow+AHKAdditions.h"

const static CGFloat kCustomIOSAlertViewDefaultButtonHeight       = 55;
const static CGFloat kCustomIOSAlertViewDefaultButtonSpacerHeight = .5f;//分割线高度
const static CGFloat kCustomIOSAlertViewCornerRadius              = 7;
const static CGFloat kCustomIOS7MotionEffectExtent                = 10.0;
const static CGFloat kAlertViewIconWidth                          = 30.0;//图标的宽度

@interface LEAlertView ()

@property(nonatomic, assign) CGFloat buttonHeight;
@property(nonatomic, assign) CGFloat buttonSpacerHeight;//分割线高度
@end

@implementation LEAlertView

- (UIColor *)titleColor {
    if (!_titleColor) {
        _titleColor = [UIColor blackColor];
    }
    return _titleColor;
}

- (id)initWithParentView: (UIView *)parentView {
    self = [self init];
    if (parentView) {
        self.frame = parentView.frame;
        self.parentView = parentView;
    }
    return self;
}

- (id)init {
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        
        _useMotionEffects = false;
        _buttonTitles = @[@"关闭"];
        
        self.buttonHeight = 0;
        self.buttonSpacerHeight = 0;
        
        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

// Create the dialog view, and animate opening the dialog
- (void)showToView:(UIView *)view {
    BOOL isSetFrame = NO;
    if (!_dialogView) {
        _dialogView = [self createContainerView];
        isSetFrame = YES;
    } else {
        CGSize screenSize = [self countScreenSize];
        CGSize dialogSize = _dialogView.frame.size;
        _dialogView.frame = CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
    }
    
    _dialogView.layer.shouldRasterize = YES;
    _dialogView.layer.rasterizationScale = [[UIScreen mainScreen] scale];
    
    self.layer.shouldRasterize = YES;
    self.layer.rasterizationScale = [[UIScreen mainScreen] scale];
    
#if (defined(__IPHONE_7_0))
    if (_useMotionEffects) {
        [self applyMotionEffects];
    }
#endif
    
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    
    [self addSubview:_dialogView];
    // Can be attached to a view or to the top most window
    // Attached to a view:
    if (_parentView != NULL) {
        [_parentView addSubview:self];
        // Attached to the top most window
    } else {
        // On iOS7, calculate with orientation
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
            UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
            switch (interfaceOrientation) {
                case UIInterfaceOrientationLandscapeLeft:
                    self.transform = CGAffineTransformMakeRotation(M_PI * 270.0 / 180.0);
                    break;
                    
                case UIInterfaceOrientationLandscapeRight:
                    self.transform = CGAffineTransformMakeRotation(M_PI * 90.0 / 180.0);
                    break;
                    
                case UIInterfaceOrientationPortraitUpsideDown:
                    self.transform = CGAffineTransformMakeRotation(M_PI * 180.0 / 180.0);
                    break;
                    
                default:
                    break;
            }
            [self setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
            
            // On iOS8, just place the dialog in the middle
        } else if (isSetFrame) {
            CGSize screenSize = [self countScreenSize];
            CGSize dialogSize = [self countDialogSize];
            CGSize keyboardSize = CGSizeMake(0, 0);
            
            _dialogView.frame = CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - keyboardSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
        }
        
        if (view) {
            [view addSubview:self];
        } else {
            [[[[UIApplication sharedApplication] windows] firstObject] addSubview:self];
        }
    }
    
    _dialogView.layer.opacity = 0.5f;
    _dialogView.layer.transform = CATransform3DMakeScale(1.3f, 1.3f, 1.0);
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4f];
        _dialogView.layer.opacity = 1.0f;
        _dialogView.layer.transform = CATransform3DMakeScale(1, 1, 1);
    } completion:NULL];
    
}

// Default button behaviour
- (void)customIOS7dialogButtonTouchUpInside: (LEAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //    NSLog(@"Button Clicked! %d, %d", (int)buttonIndex, (int)[alertView tag]);
    [self close];
}

// Dialog close animation then cleaning and removing the view from the parent
- (void)close {
    CATransform3D currentTransform = _dialogView.layer.transform;
    
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        CGFloat startRotation = [[_dialogView valueForKeyPath:@"layer.transform.rotation.z"] floatValue];
        CATransform3D rotation = CATransform3DMakeRotation(-startRotation + M_PI * 270.0 / 180.0, 0.0f, 0.0f, 0.0f);
        
        _dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1));
    }
    
    _dialogView.layer.opacity = 1.0f;
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
        self.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.0f];
        _dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6f, 0.6f, 1.0));
        _dialogView.layer.opacity = 0.0f;
    } completion:^(BOOL finished) {
        for (UIView *v in [self subviews]) {
            [v removeFromSuperview];
        }
        [self removeFromSuperview];
    }];
    
    _onButtonTouchUpInside = nil;
}

- (void)setSubView: (UIView *)subView {
    _containerView = subView;
}

#pragma mark - 创建展示view
/**
 *  Creates the container view here: create the dialog, then add the custom content and buttons
 */
- (UIView *)createContainerView {
    CGSize screenSize = [self countScreenSize];
    CGSize dialogSize = [self countDialogSize];
    
    // For the black background
    [self setFrame:CGRectMake(0, 0, screenSize.width, screenSize.height)];
    
    // This is the dialog's container; we attach the custom content and the buttons to this one
    UIView *dialogContainer = [[UIView alloc] initWithFrame:CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height)];
    
    // First, we style the dialog to match the iOS7 UIAlertView >>>
//    CAGradientLayer *gradient = [CAGradientLayer layer];
//    gradient.frame = dialogContainer.bounds;
//    gradient.colors = [NSArray arrayWithObjects: (id)[[UIColor colorWithRed:218.0/255.0 green:218.0/255.0 blue:218.0/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1.0f] CGColor], (id)[[UIColor colorWithRed:218.0/255.0 green:218.0/255.0 blue:218.0/255.0 alpha:1.0f] CGColor], nil];
//    
    CGFloat cornerRadius = kCustomIOSAlertViewCornerRadius;
//    gradient.cornerRadius = cornerRadius;
//    gradient.masksToBounds = YES;
    //    [dialogContainer.layer insertSublayer:gradient atIndex:0];
    //创建虚化背景
    UIView *blurView = [self createBlurBGView:dialogContainer.frame];
    //    blurView.layer.cornerRadius = cornerRadius;
    
    [dialogContainer addSubview:blurView];
    [blurView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
    
    dialogContainer.layer.cornerRadius = cornerRadius;
    dialogContainer.layer.masksToBounds = YES;
    dialogContainer.layer.borderColor = [[UIColor colorWithRed:198.0/255.0 green:198.0/255.0 blue:198.0/255.0 alpha:1.0f] CGColor];
    dialogContainer.layer.borderWidth = .4f;
    dialogContainer.layer.shadowRadius = cornerRadius + 5;
    dialogContainer.layer.shadowOpacity = 0.1f;
    dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius+5)/2, 0 - (cornerRadius+5)/2);
    dialogContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    dialogContainer.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:dialogContainer.bounds cornerRadius:dialogContainer.layer.cornerRadius].CGPath;
    
    if (_containerView == nil) {
        return [self alertSheetViewToView:dialogContainer];
    } else {
        //横线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, dialogContainer.bounds.size.height - self.buttonHeight - self.buttonSpacerHeight, dialogContainer.bounds.size.width, kCustomIOSAlertViewDefaultButtonSpacerHeight)];
        //    lineView.backgroundColor = [UIColor colorWithRed:198.0/255.0 green:198.0/255.0 blue:198.0/255.0 alpha:1.0f];
        lineView.backgroundColor = [UIColor grayColor];
        [dialogContainer addSubview:lineView];
        return [self alertViewToView:dialogContainer];
    }
}
/**
 *  alertView
 */
- (UIView *)alertViewToView:(UIView *)dialogContainer {
    // Add the custom container if there is any
    [dialogContainer addSubview:_containerView];
//    dialogContainer.backgroundColor = [UIColor clearColor];
    // Add the buttons too
    [self addButtonsToView:dialogContainer];
    
    return dialogContainer;
}
/**
 *  alertSheetView
 */
- (UIView *)alertSheetViewToView:(UIView *)dialogContainer {
    [self addSheetButtonsToView:dialogContainer];
    return dialogContainer;
}

// Helper function: add buttons to container
- (void)addButtonsToView: (UIView *)container {
    if (_buttonTitles==NULL) { return; }
    
    CGFloat buttonWidth = container.bounds.size.width / [_buttonTitles count];
    
    for (int i=0; i<[_buttonTitles count]; i++) {
        
        UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [closeButton setFrame:CGRectMake(i * buttonWidth, container.bounds.size.height - self.buttonHeight, buttonWidth, self.buttonHeight)];
        
        [closeButton addTarget:self action:@selector(customIOS7dialogButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [closeButton setTag:i];
        
        [closeButton setTitle:[_buttonTitles objectAtIndex:i] forState:UIControlStateNormal];
        [closeButton setTitleColor:[UIColor colorWithRed:0.0f green:0.5f blue:1.0f alpha:1.0f] forState:UIControlStateNormal];
        //        [closeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [closeButton setTitleColor:[UIColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:0.5f] forState:UIControlStateHighlighted];
        [closeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17.0f]];
        [closeButton.layer setCornerRadius:kCustomIOSAlertViewCornerRadius];
        
        [container addSubview:closeButton];
        
        //分割竖线
        UIView *middleLineView = [[UIView alloc] initWithFrame:CGRectMake(buttonWidth * (i + 1), container.bounds.size.height - _buttonHeight - _buttonSpacerHeight, self.buttonSpacerHeight, kCustomIOSAlertViewDefaultButtonHeight)];
        middleLineView.backgroundColor = [UIColor grayColor];
        [container addSubview:middleLineView];
    }
}
/**
 *  添加SheetButton
 */
- (void)addSheetButtonsToView:(UIView *)container {
    if (_buttonTitles == nil) return;
    
    CGFloat buttonWidth = container.bounds.size.width;
    CGFloat buttonY = container.bounds.size.height - _buttonHeight;
    CGFloat buttonHeight = kCustomIOSAlertViewDefaultButtonHeight + kCustomIOSAlertViewDefaultButtonSpacerHeight;
    if (self.buttonImages && self.buttonImages.count > 0) {
        CGFloat iconW = kAlertViewIconWidth;
        CGFloat iconH = iconW;
        CGFloat iconX = 20;
        CGFloat iconY = (buttonHeight - iconH)/2;
        for (int i = 0; i < [_buttonTitles count]; i++) {
            NSString *iconImageName = nil;
            if (i > _buttonImages.count - 1) {
                iconImageName = _buttonImages.lastObject;
            } else {
                iconImageName = _buttonImages[i];
            }
            UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:iconImageName]];
            iconView.frame = CGRectMake(iconX, iconY + (buttonHeight*i), iconW, iconH);
            [container addSubview:iconView];
            
            UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            
            [closeButton setFrame:CGRectMake(iconX + iconW + 16, buttonY + (buttonHeight*i), buttonWidth, buttonHeight)];
            
            [closeButton addTarget:self action:@selector(customIOS7dialogButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
            [closeButton setTag:i+1];
            
            [closeButton setTitle:[_buttonTitles objectAtIndex:i] forState:UIControlStateNormal];
            [closeButton setTitleColor:self.titleColor forState:UIControlStateNormal];
            //        [closeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [closeButton setTitleColor:[UIColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:0.5f] forState:UIControlStateHighlighted];
            [closeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17.0f]];
            [closeButton.layer setCornerRadius:kCustomIOSAlertViewCornerRadius];
            closeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            
            [container addSubview:closeButton];
            
            //横线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, buttonY + (buttonHeight*(i+1)), container.bounds.size.width, kCustomIOSAlertViewDefaultButtonSpacerHeight)];
            lineView.backgroundColor = [UIColor grayColor];
            [container addSubview:lineView];
        }
    } else {
        for (int i = 0; i < [_buttonTitles count]; i++) {
            UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            
            [closeButton setFrame:CGRectMake(0, buttonY + (buttonHeight*i), buttonWidth, buttonHeight)];
            
            [closeButton addTarget:self action:@selector(customIOS7dialogButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
            [closeButton setTag:i+1];
            
            [closeButton setTitle:[_buttonTitles objectAtIndex:i] forState:UIControlStateNormal];
            [closeButton setTitleColor:self.titleColor forState:UIControlStateNormal];
            //        [closeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [closeButton setTitleColor:[UIColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:0.5f] forState:UIControlStateHighlighted];
            [closeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17.0f]];
            [closeButton.layer setCornerRadius:kCustomIOSAlertViewCornerRadius];
            closeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
            
            [container addSubview:closeButton];
            
            //横线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, buttonY + (buttonHeight*(i+1)), container.bounds.size.width, kCustomIOSAlertViewDefaultButtonSpacerHeight)];
            lineView.backgroundColor = [UIColor grayColor];
            [container addSubview:lineView];
        }
    }
    //添加取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setFrame:CGRectMake(0, _buttonHeight - kCustomIOSAlertViewDefaultButtonHeight, buttonWidth, buttonHeight)];
    [cancelBtn addTarget:self action:@selector(customIOS7dialogButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setTag:0];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    //    [cancelBtn setTitleColor:self.titleColor forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor colorWithRed:0.0f green:0.5f blue:1.0f alpha:1.0f] forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:0.5f] forState:UIControlStateHighlighted];
    [cancelBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:17.0f]];
    [cancelBtn.layer setCornerRadius:kCustomIOSAlertViewCornerRadius];
    [container addSubview:cancelBtn];
}
/**
 *  创建背景View
 */
- (UIView *)createBlurBGView:(CGRect)frame {
    //获取屏幕快照并虚化
    UIWindow *previousKeyWindow = [UIApplication sharedApplication].keyWindow;
    UIImage *previousKeyWindowSnapshot = [previousKeyWindow ahk_snapshot];
    previousKeyWindowSnapshot = [previousKeyWindowSnapshot croppedImageAtFrame:frame];
    //添加毛玻璃背景
    UIView *blurView = [[UIImageView alloc] initWithImage:[previousKeyWindowSnapshot blurImageForAlert]];
    blurView.alpha = 0.99;
    return blurView;
}

#pragma mark -
// Button has been touched
- (void)customIOS7dialogButtonTouchUpInside:(id)sender {
//    if (delegate != NULL) {
//        [delegate customIOS7dialogButtonTouchUpInside:self clickedButtonAtIndex:[sender tag]];
//    }
    
    if (_onButtonTouchUpInside != NULL) {
        _onButtonTouchUpInside(self, (int)[sender tag]);
    }
    [self close];
}
/**
 *  self的size
 */
- (CGSize)countDialogSize {
    if (_buttonTitles != nil && [_buttonTitles count] > 0) {
        if (_style == LEAlertStyleSheet) {
            _buttonSpacerHeight = kCustomIOSAlertViewDefaultButtonSpacerHeight * (_buttonTitles.count - 1);
            _buttonHeight = kCustomIOSAlertViewDefaultButtonHeight * (_buttonTitles.count + 1) + _buttonSpacerHeight;
        } else {
            _buttonHeight       = kCustomIOSAlertViewDefaultButtonHeight;
            _buttonSpacerHeight = kCustomIOSAlertViewDefaultButtonSpacerHeight;
        }
    } else if (_buttonTitles != nil && _buttonTitles.count > 0 && _buttonImages && _buttonImages.count > 0) {
        _buttonSpacerHeight = kCustomIOSAlertViewDefaultButtonSpacerHeight * (_buttonTitles.count - 1);
        _buttonHeight = kCustomIOSAlertViewDefaultButtonHeight * (_buttonTitles.count + 1) + _buttonSpacerHeight;
    } else {
        _buttonHeight = 0;
        _buttonSpacerHeight = 0;
    }
    CGFloat width, height;
    if (_containerView) {
        width = _containerView.frame.size.width;
        height = _containerView.frame.size.height;
    } else {
        CGSize screenSize = [self countScreenSize];
        width = screenSize.width - 32;
        height = 0;
    }
    CGFloat dialogWidth = width;
    CGFloat dialogHeight = height + _buttonHeight + _buttonSpacerHeight;
    
    return CGSizeMake(dialogWidth, dialogHeight);
}

// Helper function: count and return the screen's size
- (CGSize)countScreenSize {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    
    // On iOS7, screen width and height doesn't automatically follow orientation
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
        if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
            CGFloat tmp = screenWidth;
            screenWidth = screenHeight;
            screenHeight = tmp;
        }
    }
    
    return CGSizeMake(screenWidth, screenHeight);
}

#if (defined(__IPHONE_7_0))
// Add motion effects
- (void)applyMotionEffects {
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        return;
    }
    
    UIInterpolatingMotionEffect *horizontalEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
    horizontalEffect.minimumRelativeValue = @(-kCustomIOS7MotionEffectExtent);
    horizontalEffect.maximumRelativeValue = @( kCustomIOS7MotionEffectExtent);
    
    UIInterpolatingMotionEffect *verticalEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
    verticalEffect.minimumRelativeValue = @(-kCustomIOS7MotionEffectExtent);
    verticalEffect.maximumRelativeValue = @( kCustomIOS7MotionEffectExtent);
    
    UIMotionEffectGroup *motionEffectGroup = [[UIMotionEffectGroup alloc] init];
    motionEffectGroup.motionEffects = @[horizontalEffect, verticalEffect];
    
    [_dialogView addMotionEffect:motionEffectGroup];
}
#endif

- (void)dealloc {
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

// Rotation changed, on iOS7
- (void)changeOrientationForIOS7 {
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    CGFloat startRotation = [[self valueForKeyPath:@"layer.transform.rotation.z"] floatValue];
    CGAffineTransform rotation;
    
    switch (interfaceOrientation) {
        case UIInterfaceOrientationLandscapeLeft:
            rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 270.0 / 180.0);
            break;
            
        case UIInterfaceOrientationLandscapeRight:
            rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 90.0 / 180.0);
            break;
            
        case UIInterfaceOrientationPortraitUpsideDown:
            rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 180.0 / 180.0);
            break;
            
        default:
            rotation = CGAffineTransformMakeRotation(-startRotation + 0.0);
            break;
    }
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
        _dialogView.transform = rotation;
    } completion:nil];
    
}

// Rotation changed, on iOS8
- (void)changeOrientationForIOS8: (NSNotification *)notification {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
        CGSize dialogSize = [self countDialogSize];
        CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
        self.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        _dialogView.frame = CGRectMake((screenWidth - dialogSize.width) / 2, (screenHeight - keyboardSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
    } completion:nil];
}

// Handle device orientation changes
- (void)deviceOrientationDidChange: (NSNotification *)notification {
    // If dialog is attached to the parent view, it probably wants to handle the orientation change itself
    if (_parentView != NULL) {
        return;
    }
    
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        [self changeOrientationForIOS7];
    } else {
        [self changeOrientationForIOS8:notification];
    }
}

// Handle keyboard show/hide changes
- (void)keyboardWillShow: (NSNotification *)notification {
    CGSize screenSize = [self countScreenSize];
    CGSize dialogSize = [self countDialogSize];
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation) && NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) {
        CGFloat tmp = keyboardSize.height;
        keyboardSize.height = keyboardSize.width;
        keyboardSize.width = tmp;
    }
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
        _dialogView.frame = CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - keyboardSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
    } completion:nil];
}

- (void)keyboardWillHide: (NSNotification *)notification {
    CGSize screenSize = [self countScreenSize];
    CGSize dialogSize = [self countDialogSize];
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
        _dialogView.frame = CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height);
    } completion:nil];
}

- (void)btnClick:(id)view complete:(void (^)(int index))complete {
    [self setOnButtonTouchUpInside:^(LEAlertView *alertView, int buttonIndex) {
        complete(buttonIndex);
    }];
}
@end
